<?php

/**
 * registration actions.
 *
 * @package    lbreminder
 * @subpackage registration
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class registrationActions extends sfActions
{
	/**
	 * Executes index action
	 *
	 * @param sfRequest $request A request object
	 */
	public function executeIndex(sfWebRequest $request) {
		//		$user = new sfGuardUser();
		//		$user->setUsername('puti');
		//		$user->setPassword('puti');
		//		$user->save();
	}

	public function executeNew(sfWebRequest $request) {
		$myUser = new sfGuardUser();
		$myUser->setIsActive(false);
		$this->form = new sfGuardUserForm($myUser);
	}

	public function executeCreate(sfWebRequest $request) {
		$this->form = new sfGuardUserForm();
		$lbuser = $this->processForm($request, $this->form);

		if($lbuser) {
			$username = $lbuser->getUsername();
			$id = $lbuser->getId();
			$up = $lbuser->getsfGuardUserProfiles();
			$vcode = $up[0]->getVCode();
			$email = $up[0]->getEmail();
			$this->sendVCodeMail($id, $username, $email, $vcode);
			$this->setTemplate('emailSent');
		} else {
			$this->setTemplate('new');
		}
	}

	public function executeActivateAccount(sfWebRequest $request) {

		if($request->hasParameter('id')) {
			$id = $request->getParameter('id');
			$username = $request->getParameter('username');
			$vcode = $request->getParameter('vcode');
			$this->logMessage($id .'--'. $username .'--'. $vcode, 'debug');
			$lbuser = sfGuardUserPeer::retrieveByPK($id);
			
			if (!$lbuser) {
				$this->activationResult = 'fail';
				return;
			}
			
			$up = $lbuser->getsfGuardUserProfiles();
			$actualVcode = $up[0]->getVCode();
			
			if (!strcmp($lbuser->getUsername(),$username) && !strcmp($actualVcode, $vcode)) {
				$this->activationResult = 'successful';
				
				if (!$lbuser->getIsActive()) {
					$lbuser->setIsActive(true);
					$lbuser->save();
				}
			} else {
				$this->activationResult = 'failed';
			}
		}
	}

	protected function processForm(sfWebRequest $request, sfForm $form)	{
		$lbuser = null;

		$form->bind(
		$request->getParameter($form->getName()),
		$request->getFiles($form->getName())
		);

		if ($form->isValid()) {
			$lbuser = $form->save();
		}

		return $lbuser;
	}

	private function sendVCodeMail($id, $username, $email, $vcode) {
		$message = $this->getMailer()->compose();
		$message->setSubject('Location Based Reminder : Activation Code');
		$message->setTo($email);
		$message->setFrom(array('lbreminder@app.com' => sfConfig::get('app_product_name')));
		$html = $this->getPartial('vcodeMailTemplate',array('id' => $id,'username' => $username, 'vcode' => $vcode));
		$message->setBody($html, 'text/html');
		$this->getMailer()->send($message);
	}
}











